package com.tieshan.smartwindow.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.*
import android.graphics.SurfaceTexture
import android.media.Image
import android.media.MediaPlayer
import android.os.*
import android.text.TextUtils
import android.util.Log
import android.view.MotionEvent
import android.view.Surface
import android.view.TextureView
import android.view.View
import android.view.View.OnTouchListener
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.LinearInterpolator
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import com.tieshan.smartwindow.R
import com.tieshan.smartwindow.app.AppActivity
import com.tieshan.smartwindow.bean.FileNameBean
import com.tieshan.smartwindow.other.ALPermissionManager.watchDog
import com.tieshan.smartwindow.other.pisutil.CRC16Utils
import com.tieshan.smartwindow.other.pisutil.UDPData
import com.tieshan.smartwindow.other.pisutil.UDPDataUtil
import com.tieshan.smartwindow.other.*
import com.tieshan.smartwindow.service.FtpService
import com.tieshan.smartwindow.service.PisService
import com.tieshan.smartwindow.service.PisService_Cong
import com.tieshan.smartwindow.widget.MainTopView_Left
import com.tieshan.smartwindow.widget.MainTopView_Right
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.io.*
import java.util.*
import kotlin.collections.ArrayList


/**
 * author : Hleo
 * time   : 2022/2/9
 * desc   : 首页显示
 *
 */
@ExperimentalStdlibApi
class MainActivity : AppActivity() {
    companion object {
        //蒲公英版本是否更新
        @SuppressLint("StaticFieldLeak")
        var context: Activity? = null
//        var isSameStation:Boolean=true //是否是同一站点推送心跳包
    }

    //是否是待机页面，是待机页面则不更新首页UI
    var isDaiji = false

    private val mmkv: MMKV = MMKV.mmkvWithID(MMKVConfig.TimesID)
    private val mmLive: MMKV = MMKV.mmkvWithID(MMKVConfig.LiveContent)
    var ip = ""
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        context = this
        initHomeVideo()
        initVideoClick()
        initHandler()
        initFtp()
        initAnim()
        updateText()
        startWatchDog()
        iv_home.setOnClickListener {
            //点击以后，延迟3分钟显示桌面
            hasFirst = true
            mChangeIndex = 0
            startAlphaTopBottom(true)
        }
        iv_window.setOnClickListener {
            startActivity(WindowActivity::class.java)

        }
        topView_left.leavelistener = object : MainTopView_Left.isLeaveListener {
            override fun leaveListener() {
                hasFirst = true
                mChangeIndex = 0
                startAlphaTopBottom(true)
            }

            override fun endListener() {
                hasFirst = true
                mChangeIndex = 0
                startAlphaTopBottom(true)
            }
        }
        topView_right.leavelistener = object : MainTopView_Right.isLeaveListener {
            override fun leaveListener() {
                hasFirst = true
                mChangeIndex = 0
                startAlphaTopBottom(true)
            }

            override fun endListener() {
                hasFirst = true
                mChangeIndex = 0
                startAlphaTopBottom(true)
            }
        }
    }
    private fun initVideoClick() {
        tv_last.setOnClickListener {
            if (DoubleClickHelper.isOnDoubleClick())
                return@setOnClickListener
            hasFirst = true
            mChangeIndex = 0
            videoIndex--
            if (videoIndex <= 0) {
                videoIndex = filedatas!!.size - 1
            }
            playPosition()
        }
        tv_next.setOnClickListener {
            if (DoubleClickHelper.isOnDoubleClick())
                return@setOnClickListener
            hasFirst = true
            mChangeIndex = 0
            videoIndex++
            if (videoIndex >= filedatas!!.size - 1) {
                videoIndex = 0
            }
            playPosition()
        }
    }

    //根据IP是奇数还是偶数获取设备显示方向，奇数显示left，偶数显示right
    private fun initIp() {
        if (!TextUtils.isEmpty(ip) && ip.length > 0) {
            var lastip = ip!!.substring(ip!!.length - 1, ip!!.length - 0)
            try {
                if (lastip.toInt() % 2 == 1) {
                    if (jihuoCode == 2) {
                        if (topView_right.visibility == View.VISIBLE) topView_right.visibility =
                            View.GONE
                        if (topView_left.visibility == View.GONE) topView_left.visibility =
                            View.VISIBLE
                    } else {
                        if (topView_right.visibility == View.GONE) topView_right.visibility =
                            View.VISIBLE
                        if (topView_left.visibility == View.VISIBLE) topView_left.visibility =
                            View.GONE
                    }
                } else {
                    if (jihuoCode == 2) {
                        if (topView_right.visibility == View.GONE) topView_right.visibility =
                            View.VISIBLE
                        if (topView_left.visibility == View.VISIBLE) topView_left.visibility =
                            View.GONE
                    } else {
                        if (topView_right.visibility == View.VISIBLE) topView_right.visibility =
                            View.GONE
                        if (topView_left.visibility == View.GONE) topView_left.visibility =
                            View.VISIBLE
                    }
                }
            } catch (e: Exception) {
            }
        }

    }

    var alphaAnimation: AlphaAnimation? = AlphaAnimation(1.0f, 0.0f)
    private fun initAnim() {
        iv_home!!.visibility = View.INVISIBLE
        alphaAnimation!!.duration = 5000
        alphaAnimation!!.repeatMode = Animation.REVERSE
        alphaAnimation!!.repeatCount = Animation.INFINITE
        alphaAnimation!!.interpolator = LinearInterpolator()
        iv_home!!.setAnimation(alphaAnimation)
        alphaAnimation!!.start()
    }

    private fun initTimesLOG(date: UDPData.TimeSpeedData) {
        try {
            val time = mmkv.getInt(MMKVConfig.TimesID, 0)
            if (time == 0) return
            var str = ""
            if (time < 60) str = "${time}分钟"
            else if (time > 60) str = "${time / 60}小时${time % 60}分钟"
            val timefile = "${date.year}-${date.month}"
            val fileName = "${date.year}年${date.month}月${date.day}日"
            FileUtil.writeFile(
                "${FileConfig.TIMESLogPath}/$timefile",
                "${fileName}运行日志",
                "智能车窗系统已持续运行$str",
            )
        } catch (e: Exception) {
            Timber.e(e)
        }
    }

    //心跳监听handler,每秒钟请求一次，超过30秒，则表示handler
    private var runTimsHandler: Handler? = null
    var runtimesableheart: Runnable = object : Runnable {
        override fun run() {
            var runtimes = mmkv.getInt(MMKVConfig.TimesID, 0)
            runtimes = runtimes + 1
            mmkv.putInt(MMKVConfig.TimesID, runtimes)
            runTimsHandler!!.postDelayed(this, 600000)
        }
    }

    //本地获取的视频集合
    val filedatas: ArrayList<FileNameBean>? = arrayListOf()
    var player: MediaPlayer? = null

    private fun log(msg:String){
        Log.e("main_page",msg)
        FileUtil.writeLog("test_log",msg)
    }
    //获取首页视频文件并播放
    private fun initHomeVideo() {
        try {
            val files = File(FileConfig.MainVideoPath)
            log("path ${files.absolutePath}  ${files.exists()}")
            if (!files.exists()) files.mkdirs()
            val list = files.listFiles()?:return
            log("new file ${list.size}")
            if (list != null && list.size != 0) {
                for (index in 0..list.size - 1) {
                    val path = list[index].name
                    val bean = FileNameBean()
                    bean.name = path
                    bean.path = list[index].path
                    filedatas!!.add(bean)
                }
                Collections.sort(filedatas, object : Comparator<FileNameBean?> {
                    override fun compare(o1: FileNameBean?, o2: FileNameBean?): Int {
                        return o1!!.sort - o2!!.sort
                    }
                })
                player = MediaPlayer()
                player!!.setDataSource(filedatas!![0].path)
                player!!.prepareAsync()
                player!!.setOnPreparedListener {
                    it.start()
                }
                playVideo()
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    //播放视频
    private fun playVideo() {
        playPosition()
        video_viewmain.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                surface: SurfaceTexture, width: Int, height: Int
            ) {
                player!!.setSurface(Surface(surface))

            }

            override fun onSurfaceTextureSizeChanged(
                surface: SurfaceTexture, width: Int, height: Int
            ) {
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                if (player != null) {
                    player!!.release()
                }
                return false
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
            }
        }
    }

    var videoIndex = -1
    private fun playPosition() {
        log("playPosition file size ${filedatas?.size}  index ${videoIndex}")
        if (filedatas == null || filedatas!!.size == 0 || player == null)
            return
        if (player != null)
            player!!.release()
        player = MediaPlayer()
        if (videoIndex == -1)
            player!!.setDataSource(filedatas!![0]!!.path)
        else
            player!!.setDataSource(filedatas!![videoIndex]!!.path)

        player!!.prepareAsync()
        player!!.setOnCompletionListener {
            if (videoIndex == -1)
                videoIndex = 0
            if (videoIndex < filedatas!!.size - 1)
                videoIndex++
            else
                videoIndex = 0
            log("OnCompletionListener index ${videoIndex}")
            playPosition()
        }
        player!!.setOnPreparedListener {
            if (videoIndex != -1)
                player!!.setSurface(Surface(video_viewmain.surfaceTexture))
            if(isDaiji.not()){
                log("playPosition start")
                player!!.start()
            }
        }
    }

    private fun initFtp() {
        startService(Intent(this, FtpService::class.java))
    }

    private fun setPoint() {
        tv_point1.visibility =
            if (tv_point1.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
        tv_point2.visibility =
            if (tv_point2.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
        tv_point3.visibility =
            if (tv_point3.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
        tv_point4.visibility =
            if (tv_point4.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
        tv_point5.visibility =
            if (tv_point5.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
        topView_left.setPoint()
        topView_right.setPoint()
    }

    override fun onPause() {
        super.onPause()
//        player!!.pause()
    }

    override fun onResume() {
        super.onResume()
//        player!!.start()
        mChangeHandler!!.removeCallbacks(runnablechange)
        mChangeHandler!!.postDelayed(runnablechange, 1000L)

    }

    override fun onLowMemory() {
        System.gc()
        super.onLowMemory()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (player != null)
            player!!.release()
        EventBus.getDefault().unregister(this)
        stopService(Intent(this, FtpService::class.java))
        runTimsHandler!!.removeCallbacks(runtimesableheart)
    }

    override fun initData() {
        if (intent != null && intent.getStringExtra("ip") != null) {
            ip = intent!!.getStringExtra("ip")!!
        }
        //延迟获取PIS数据
        Handler(Looper.getMainLooper()).postDelayed({
            bindService(
                Intent(this@MainActivity, PisService::class.java), conn, Context.BIND_AUTO_CREATE
            )
            bindService(
                Intent(this@MainActivity, PisService_Cong::class.java),
                conCon,
                Context.BIND_AUTO_CREATE
            )
        }, 2000)
        EventBus.getDefault().register(this)
    }

    //心跳监听handler,每秒钟请求一次，超过30秒，则表示handler
    private var mHeartHandler: Handler? = null
    private var mHeartIndex = 0
    var jihuoCode = 0
    var reboot = false

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(data: UDPData) {
        GlobalScope.launch(Dispatchers.Main) {
            mHeartIndex = 0  //收到数据，表明心跳正常
            topView_left.setAtStation(data)
            topView_right.setAtStation(data)
            when (CRC16Utils.bytesToHexString(data.functionCode)) {
                UDPDataUtil.functionCode.heartCode -> {
                    jihuoCode = data.heart!!.jihuoCode
                    initIp()
                }
            }
            if (data.isReboot&&reboot==false) {
                reboot=true
                watchDog()
                delay(1000)
                ALPermissionManager.reBoot()
            }
            try {
                setSystemTime(data)
            } catch (e: Exception) {
            }
        }
    }


    //设置系统时间
    @SuppressLint("TimberArgCount")
    private fun setSystemTime(data: UDPData) {
        //如果设备时间是准点时间，则对时间进行校准
        if (data.timeSpeed == null) {
            return
        }
        //判断如果年份长度不是4，则年份格式有问题，不更新
        if (data!!.timeSpeed!!.year == null || data!!.timeSpeed!!.year.toString().length != 4) return
        if (data!!.timeSpeed!!.month == null || data!!.timeSpeed!!.month > 12 || data!!.timeSpeed!!.month < 0 || data!!.timeSpeed!!.month.toString().length > 2) return
        if (data!!.timeSpeed!!.day == null || data!!.timeSpeed!!.day > 31 || data!!.timeSpeed!!.day < 0 || data!!.timeSpeed!!.day.toString().length > 2) return
        if (data!!.timeSpeed!!.hour == null || data!!.timeSpeed!!.hour > 24 || data!!.timeSpeed!!.hour < 0 || data!!.timeSpeed!!.hour.toString().length > 2) return
        if (data!!.timeSpeed!!.min == null || data!!.timeSpeed!!.min > 60 || data!!.timeSpeed!!.min < 0 || data!!.timeSpeed!!.min.toString().length > 2) return
        if (data!!.timeSpeed!!.sec == null || data!!.timeSpeed!!.sec > 60 || data!!.timeSpeed!!.sec < 0 || data!!.timeSpeed!!.sec.toString().length > 2) return
        initTimesLOG(data!!.timeSpeed!!)
        val hour = data.timeSpeed!!.hour
        val min = data.timeSpeed!!.min
        val month = data.timeSpeed!!.month
        val day = data.timeSpeed!!.day
        val year = data.timeSpeed!!.year
//        strtime+=" 设置完毕\n"
        if (hour >= 0 && hour <= 60) {
            val hourstr = "${String.format("%02d", hour)}"
            if (!tv_time1.text.equals(hourstr)) {
                tv_time1.text = hourstr
                tv_time2.text = hourstr
                tv_time3.text = hourstr
                tv_time4.text = hourstr
                tv_time5.text = hourstr
            }
        }
        if (min >= 0 && min <= 60) {
            val minutestr = "${String.format("%02d", min)}"
//        如果文本一样，则不更新UI
            if (!tv_time11.text.equals(minutestr)) {
                tv_time11.text = minutestr
                tv_time22.text = minutestr
                tv_time33.text = minutestr
                tv_time44.text = minutestr
                tv_time55.text = minutestr
            }
        }
        if (month >= 0 && day >= 0 && month <= 12 && day <= 31 && year > 2000 && year < 2100) {
            val yearstr = "$year/${
                String.format(
                    "%02d", month
                )
            }/${String.format("%02d", day)}"
            if (!tv_year1.text.equals(yearstr)) {
                tv_year1.text = yearstr
                tv_year2.text = yearstr
                tv_year3.text = yearstr
                tv_year4.text = yearstr
                tv_year5.text = yearstr
            }
        }
        topView_left.setTime(data)
        topView_right.setTime(data)
    }


    private val conn: ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName) {
        }

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val binder: PisService.SimpleBinder = service as PisService.SimpleBinder
            val bindService: PisService = binder.service
            bindService.pisMessageListener()
        }
    }
    private val conCon: ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName) {
        }

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val binder: PisService_Cong.SimpleBinder = service as PisService_Cong.SimpleBinder
            val bindService: PisService_Cong = binder.service
            bindService.pisMessageListener()
        }
    }

    private fun initHandler() {
        mHeartHandler = Handler(Looper.getMainLooper())
        mHeartHandler!!.postDelayed(runnableheart, 1000)
        mChangeHandler = Handler(Looper.getMainLooper())

        runTimsHandler = Handler(Looper.getMainLooper())
        runTimsHandler!!.postDelayed(runtimesableheart, 60000)
    }

    var textIndex = 0

    //页面切换handler，每30秒切换一次。
    private var mChangeHandler: Handler? = null

    //页面切换角标
    var mChangeIndex = 0

    //生命信号
    var mLiveIndex = 0


    //是否是初次开机
    var hasFirst = true
    val openDog = MMKV.mmkvWithID(MMKVConfig.openDog).getBoolean(MMKVConfig.openDog, true)
    var runnablechange: Runnable = object : Runnable {
        override fun run() {
            mChangeIndex++
            //初次开机，3分钟内再切换屏保
            if (mChangeIndex == 180 && hasFirst == true) {
                hasFirst = false
                startAlphaTopBottom(false)
            }
            textIndex++
            if (textIndex == 26)
                textIndex = 0
            var livelog = MMKV.mmkvWithID(MMKVConfig.LiveLog).getBoolean(MMKVConfig.LiveLog, false)
            if (livelog) {
                if (mLiveIndex % 600 == 0) {
                    var liveLog = mmLive.getString(MMKVConfig.LiveContent, "");
                    var year = if (!TextUtils.isEmpty(tv_year1.text)) tv_year1.text else ""
                    var hour = if (!TextUtils.isEmpty(tv_time1.text)) tv_time1.text else ""
                    var min = if (!TextUtils.isEmpty(tv_time11.text)) tv_time11.text else ""
                    liveLog += "$year ${hour}时:${min}分 记录日志，日志内容 （运行次数=${mLiveIndex % 600}） \n"
                    mmLive.putString(MMKVConfig.LiveContent, liveLog)
                    if (!year.equals("0000-00-00") && year.length >= 0)
                        FileUtil.writeLogFile(
                            FileConfig.LiveLogPath,
                            "$year-${MMKVConfig.LiveLog}",
                            liveLog!!
                        )
                }
                mLiveIndex++
            }
            mChangeHandler!!.postDelayed(this, 1000)
        }
    }

    var al: AlphaAnimation? = AlphaAnimation(0.0f, 1.0f)
    var alindex = 1
    private fun updateText() {
        al!!.duration = 3000
        al!!.repeatMode = Animation.REVERSE
        al!!.repeatCount = Animation.RESTART
        al!!.interpolator = LinearInterpolator()
        al!!.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {

            }

            override fun onAnimationEnd(animation: Animation?) {
                if (alindex == 1) {
                    ll1!!.startAnimation(al)
                } else if (alindex == 2) {
                    ll2!!.startAnimation(al)
                } else if (alindex == 3) {
                    ll3!!.startAnimation(al)
                } else if (alindex == 4) {
                    ll4!!.startAnimation(al)
                } else if (alindex == 5) {
                    ll5!!.startAnimation(al)
                }
                alindex++
                if (alindex == 6)
                    alindex = 1

            }

            override fun onAnimationRepeat(animation: Animation?) {
            }

        })
        view!!.startAnimation(al)
    }

    var runnableheart: Runnable = object : Runnable {
        override fun run() {
            mHeartIndex++
            setPoint()
            if (mHeartIndex >= 30) {
                //如果断线时间大于30秒，则显示成都欢迎您的文本
                topView_left.showDisconnctContent()
                topView_right.showDisconnctContent()
            }
            mHeartHandler!!.postDelayed(this, 1000)
        }
    }


    //视频及日期显示
    fun startAlphaTopBottom(bo: Boolean) {
        try {
            isDaiji = !bo
            if (bo) {
                mChangeIndex = 0
                cl_main.visibility = View.VISIBLE
                cl_time.visibility = View.GONE
                if (player != null){
                    log("startAlphaTopBottom start")
                    player!!.start()
                }
            } else {
                cl_time.visibility = View.VISIBLE
                cl_main.visibility = View.GONE
                if ( player?.isPlaying == true){
                    log("startAlphaTopBottom pause")
                    player!!.pause()
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    private fun startWatchDog(){
        lifecycleScope.launch {
            while (openDog){
                watchDog()
                delay(60*1000)
            }
        }
    }


}

